package com.hongxun.design.ui.dragview;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hongxun.design.MyApp;
import com.hongxun.design.bean.BeforeExpItemBean;
import com.hongxun.design.bean.Exploration;
import com.hongxun.design.bean.PhotoPassagewayItemBean;
import com.hongxun.design.bean.photopassbean.PhotoPassIconBean;
import com.hongxun.design.bean.photopassbean.SystemTypeBean;
import com.hongxun.design.constant.Constant;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.MyDecimalFormat;
import com.hongxun.design.mytools.MyLog;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.object_properties.MyMessage;
import com.hongxun.design.ui.dialogstyle.MyDialog;
import com.hongxun.design.utils.DensityUtil;
import com.hongxun.design.utils.InputUtil;
import com.hongxun.design.utils.dragutil.DragWithUtil;
import com.hongxun.design.utils.fastjson.FastJsonUtil;
import com.hongxun.design.utils.fileutil.GetFileUtil;
import com.hongxun.design.utils.fileutil.SetFileUtil;
import com.hongxun.design.utils.httputil.HttpStringUtil;
import com.hongxun.design.utils.httputil.PostParams;

import java.util.List;
import java.util.Set;

import static com.hongxun.design.mytools.MString.up;

/**
 * Created by zerdoor_pc on 2016/5/17.
 * 拖动后的处理类
 */
public class AddDragIcon {
    PhotoPassagewayItemBean itemBean;
    Context context;
    RelativeLayout addimage;
    int type;

    TextImageItem imageView;
    private Handler CorrChannelFeatureHandler;//关联通道特征id接收器
    private Handler queryChannelFeatureHandler;//关联通道特征信息接收器
    private Handler addaddChannelFeatureHandler;//新增通道特征信息接收器
    private Handler upChannelFeatureHandler;//修改信息接收器
    private Handler delChannelFeatureHandler;//删除接收器

    public AddDragIcon() {

    }

    public void setData(PhotoPassagewayItemBean curritemBean, Context context, RelativeLayout addimage, int type) {
        MyLog.L(MString.SUCCESSED + " itemBean11=" + JSON.toJSONString(itemBean));
        if (itemBean == null) itemBean = new PhotoPassagewayItemBean();
        MyLog.L(MString.SUCCESSED + " itemBean22=" + JSON.toJSONString(itemBean));
        this.itemBean.setBean(curritemBean);

        MyLog.L(MString.SUCCESSED + " itemBean33=" + JSON.toJSONString(itemBean));
        this.context = context;
        this.addimage = addimage;
        this.type = type;
        addUpChannelFeatureHandler();//保存handler
        addDelChannelFeatureHandler();//删除handler
        addQueryChannelFeatureHandler();//查询数据handler
        exploration_id = MyApp.currExploration.getExploration_id();
        switch (type) {
            case Constant.TYPE_TOP:
                addCorrChannelFeatureHandler();//关联点
                handler.sendEmptyMessage(Constant.DRAGTOP);
                break;
            case Constant.TYPE_GRID:
                addaddChannelFeatureHandler();
                handler.sendEmptyMessage(Constant.DRAGDOWN);
                break;
            case Constant.TYPE_ADD:
                addImage(itemBean, context, addimage);
                break;
        }


    }

    String exploration_id = "";

    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Constant.OPENDIALOG:
                    openDialog();//打开dialog
                    break;
                case Constant.DIALOGBACK://dialog返回加载图标
                    InputUtil.closeInput((Activity) context);
                    UpChannelFeature();
                    //MyApp.HTTP.UpChannelFeature(upChannelFeatureHandler, HttpStringUtil.SUCCESSED, itemBean.getChannel_id(), itemBean.getDialogBean());//修改通道信息
                    break;
                case Constant.DELECT://删除图标
                    InputUtil.closeInput((Activity) context);
                    DelChannelFeature();
                    //MyApp.HTTP.DelChannelFeature(delChannelFeatureHandler, HttpStringUtil.SUCCESSED, itemBean.getChannel_id());//删除通道信息
                    break;
                case Constant.DRAGTOP://关联
                    CorrChannelFeature();
                    //MyApp.HTTP.CorrChannelFeature(CorrChannelFeatureHandler, HttpStringUtil.SUCCESSED, itemBean.exploration_id, exploration_id);
                    break;
                case Constant.DRAGDOWN:// 新增
                    AddChannelFeature();
                    //MyApp.HTTP.AddChannelFeature(addaddChannelFeatureHandler, HttpStringUtil.SUCCESSED, itemBean.getPt_id(), exploration_id, itemBean.getDistance());
                    break;
            }
        }
    };

    /**
     * 关联点*
     */
    private void addCorrChannelFeatureHandler() {
        CorrChannelFeatureHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        String s = FastJsonUtil.JsonToCheck_String((String) msg.obj);
                        if (s.equals(MString.TRUE) || (s.equals(MString.FALSE) && !((String) msg.obj).contains("code"))) {
                            String channel_id = FastJsonUtil.JsonToGetChannel_id((String) msg.obj);
                            itemBean.setChannel_id(channel_id);
                            //handler.sendEmptyMessage(Constant.OPENDIALOG);//打开dialog
                            if (imageView == null) {
                                addImage(itemBean, context, addimage);
                            }
                            MyApp.HTTP.QueryChannelFeature(queryChannelFeatureHandler, HttpStringUtil.SUCCESSED, channel_id);
                        } else {
                            ToastShow.showShort(context, s);
                        }
                        break;
                    case 1:

                        break;
                    case HttpStringUtil.ERROR:
                        ToastShow.showShort(context, (String) msg.obj);
                        break;
                }
            }
        };
    }

    com.alibaba.fastjson.JSONObject data;

    /**
     * 查询关联数据*
     */
    private void addQueryChannelFeatureHandler() {
        queryChannelFeatureHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        MyLog.L(MString.SUCCESSED + " msg.obj=" + msg.obj);
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            JSONObject object = JSON.parseObject((String) msg.obj);
                            if (object != null && object.size() > 0) {
                                String o = object.get("pt").toString();
                                data = JSON.parseObject(o);

                            }
                            handler.sendEmptyMessage(Constant.OPENDIALOG);//打开dialog
                        } else {
                            ToastShow.showShort(context, FastJsonUtil.JsonToCheck_String((String) msg.obj));
                        }
                        break;
                    case HttpStringUtil.ERROR:
                        ToastShow.showShort(context, (String) msg.obj);
                        break;
                }
            }
        };
    }


    /**
     * 新增点*
     */
    private void addaddChannelFeatureHandler() {
        addaddChannelFeatureHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            String channel_id = FastJsonUtil.JsonToGetChannel_id((String) msg.obj);
                            itemBean.setChannel_id(channel_id);
                            MyLog.L(MString.SUCCESSED + "设置 channel_id=" + channel_id + " obj=" + msg.obj);
                            handler.sendEmptyMessage(Constant.OPENDIALOG);//打开dialog
                            if (imageView == null) {
                                addImage(itemBean, context, addimage);
                            }
                        } else {
                            ToastShow.showShort(context, FastJsonUtil.JsonToCheck_String((String) msg.obj));
                        }
                        break;
                    case HttpStringUtil.ERROR:
                        ToastShow.showShort(context, (String) msg.obj);
                        break;
                }
            }
        };
    }

    /**
     * 修改通道信息*
     */
    private void addUpChannelFeatureHandler() {
        upChannelFeatureHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        String error = FastJsonUtil.JsonToCheck_String((String) msg.obj);
                        if (error.equals(MString.TRUE)) {
                            ToastShow.showShort(context, "保存成功!");
                        } else {

                            ToastShow.showShort(context, error);
                        }
                        break;
                    case HttpStringUtil.ERROR:
                        ToastShow.showShort(context, (String) msg.obj);
                        break;
                }
            }
        };
    }

    /**
     * 删除通道信息*
     */
    private void addDelChannelFeatureHandler() {
        delChannelFeatureHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        String error = FastJsonUtil.JsonToCheck_String((String) msg.obj);
                        if (error.equals(MString.TRUE)) {
                            addimage.removeView(imageView);
                            ToastShow.showShort(context, "删除成功!");
                        } else {
                            ToastShow.showShort(context, error);
                        }
                        break;
                    case HttpStringUtil.ERROR:
                        ToastShow.showShort(context, (String) msg.obj);
                        break;
                }
            }
        };
    }


    @SuppressLint("NewApi")
    public void addImage(final PhotoPassagewayItemBean itemBean, Context context, RelativeLayout addimage) {
        RelativeLayout.LayoutParams l = new RelativeLayout.LayoutParams(itemBean.getXy()[0], itemBean.getXy()[1]);
        imageView = new TextImageItem(context);
        imageView.setImage(itemBean.getUrlSeleck());
        imageView.setName(MyDecimalFormat.getDouble(Double.parseDouble(itemBean.getDistance()), "0.0"));
        imageView.setX(itemBean.getXy()[0]);
        imageView.setY(imageView.getY() + addimage.getHeight() / 8);
        l.width = DensityUtil.dip2px(context, 24);
        l.height = DensityUtil.dip2px(context, 50);
        addimage.addView(imageView, l);
        int[] s = new int[2];
        addimage.getLocationOnScreen(s);
        s[1] = s[0] + addimage.getWidth();
        DragWithUtil dragUtil = new DragWithUtil(context, imageView, s, itemBean, addimage, l, xyhandler);//设置拖拽属性
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (type) {
                    case Constant.TYPE_ADD://信息查询
                        QueryChannelFeature();
                        break;
                    case Constant.TYPE_TOP:
                        QueryChannelFeature();
                        break;
                    default:
                        openDialog();
                        break;
                }

                imageView = (TextImageItem) view;
            }
        });
    }

    private Handler xyhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case 1:
                    updateDistance();
                    break;
                case HttpStringUtil.SUCCESSED:
                    if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                        itemBean.setDistance(updateDistance);
                        addimage.removeView(imageView);
                        addImage(itemBean, context, addimage);

                    } else {

                    }

                    break;
                case HttpStringUtil.ERROR:
                    break;
            }


        }
    };
    String updateDistance = "";

    private void updateDistance() {
        updateDistance = (MyPassagewayDragView.Level * itemBean.getXy()[0]) + "";
        if (MyApp.isOnLine){
            MyApp.HTTP.upExpDistance(xyhandler, HttpStringUtil.SUCCESSED, itemBean.getExploration_id(), updateDistance);
        }else{
            itemBean.setDistance(updateDistance);
            addimage.removeView(imageView);
            addImage(itemBean, context, addimage);
            UpChannelFeature();
            SetFileUtil.updateChannelList(itemBean);//更新特征点列表
        }
    }

    /**http**/
    /**
     * 查询特征点信息*
     */
    private void QueryChannelFeature() {
        if (MyApp.isOnLine) {
            MyApp.HTTP.QueryChannelFeature(queryChannelFeatureHandler, HttpStringUtil.SUCCESSED, itemBean.getChannel_id());
        } else {
            //读取缓存
            //ToastShow.showShort(context, "查询特征点信息！");
            queryChannelFeatureHandler.sendMessage(MyMessage.getMessage(HttpStringUtil.SUCCESSED, GetFileUtil.getQueryChannelFeature(itemBean)));
        }
    }

    /**
     * 修改通道信息*
     */

    private void UpChannelFeature() {
        if (MyApp.isOnLine) {
            MyApp.HTTP.UpChannelFeature(upChannelFeatureHandler, HttpStringUtil.SUCCESSED, itemBean.getChannel_id(), itemBean.getDialogBean());//修改通道信息
        } else {
            //更新缓存
            //ToastShow.showShort(context, "修改通道！");
            PostParams.UpChannelFeature(MString.getValueId(itemBean.getChannel_id(), itemBean.getUUID()), itemBean.getDialogBean());
            String id = MString.getValueId(itemBean.getExploration_id(), itemBean.getExploration_uuid());
            List<Exploration> list = GetFileUtil.getExplorationList(MyApp.currExploration.getPoint_type());
            BeforeExpItemBean bean = FastJsonUtil.JsonToGetExploration_Id(GetFileUtil.getBeforeExp(MyApp.currExploration));
            Exploration c = new Exploration();
            c.setPhotoPassagewayItemBean(itemBean, bean);
            c.setPoint_type(MyApp.currExploration.getPoint_type());
            c.setPt_type(Constant.TEZHENGPOINT);
            for (Exploration e : list) {
                if ((e.getExploration_id().length() > 0 && !e.getExploration_id().equals(MString.code_zero)) && (e.getExploration_id().equals(id) || e.getUuid().equals(id))) {
                    c.setBeanToHas(e);
                    if (e.getExploration_id().equals(id)) {
                        c.setFlag(up);
                    } else {
                        c.setFlag(MString.add);
                    }
                    break;
                }
            }
            if (c.getPt_objectid().length() == 0) {
                String uuid = MString.getMyUUID();
                if (PostParams.map.get(MString.id) == null || (PostParams.map.get(MString.id).equals(MString.code_null) && PostParams.map.get(MString.uuid).equals(MString.code_null))) {
                    PostParams.map.put(MString.id, "");
                    PostParams.map.put(MString.uuid, uuid);
                    PostParams.map.put(MString.flag, MString.add);
                    c.setPt_objectid(uuid);
                } else if (!PostParams.map.get(MString.uuid).equals(MString.code_null)) {
                    c.setPt_objectid(PostParams.map.get(MString.uuid) + "");
                }
            }
            JSONObject c_json = JSONObject.parseObject(JSON.toJSONString(c));
            JSONObject pt = JSONObject.parseObject(c_json.getString(MString.pt));
            if (pt == null) pt = new JSONObject();
            Object[] keys = PostParams.map.keySet().toArray();

            for (Object s : keys) {
                pt.put(s.toString(), PostParams.map.get(s.toString()));
            }
            c_json.put(MString.pt, pt);
            String time = System.currentTimeMillis() + "";
            c_json.put(MString.create_time, time);
            SetFileUtil.setExplorationInfo(JSON.toJSONString(c_json), id);

        }
    }

    /**
     * 删除通道信息*
     */
    private void DelChannelFeature() {
        if (MyApp.isOnLine) {
            MyApp.HTTP.DelChannelFeature(delChannelFeatureHandler, HttpStringUtil.SUCCESSED, itemBean.getChannel_id());//删除通道信息
        } else {
            //读取缓存
            //ToastShow.showShort(context, "删除通道！");
            //1、删除列表数据。2、删除channelAList数据。3、删除基本信息
            addimage.removeView(imageView);
            // String exploration_id = itemBean.getExploration_id();
            String exploration_id = MString.getValueId(itemBean.getExploration_id(), itemBean.getExploration_uuid());
            SetFileUtil.delectChannelList(exploration_id, itemBean);//删除图标列表
            SetFileUtil.delectExplorationList(exploration_id, MyApp.currExploration.getPoint_type());//删除点集列表
            SetFileUtil.delectExploration(itemBean.getExploration_id(), itemBean.getExploration_uuid());//删除文件
            ToastShow.showShort(context, "删除成功!");
        }
    }

    /**
     * 关联通道*
     */

    private void CorrChannelFeature() {
        if (MyApp.isOnLine) {
            MyApp.HTTP.CorrChannelFeature(CorrChannelFeatureHandler, HttpStringUtil.SUCCESSED, itemBean.exploration_id, exploration_id);
        } else {
            //读取缓存
            ToastShow.showShort(context, "离线模式下无法进行此操作！");
        }
    }

    /**
     * 新增通道*
     */

    private void AddChannelFeature() {
        if (MyApp.isOnLine) {
            MyApp.HTTP.AddChannelFeature(addaddChannelFeatureHandler, HttpStringUtil.SUCCESSED, itemBean.getPt_id(), exploration_id, itemBean.getDistance());
        } else {
            //读取缓存
            //  ToastShow.showShort(context,"新增通道！");

            String channel_id = "";
            String uuid = MString.getMyUUID();

            String exploration_id = "";
            String exploration_uuid = MString.getMyUUID();

//            String feature_id = "";
//            String feature_uuid = MString.getMyUUID();

            itemBean.setChannel_id(channel_id);
            itemBean.setUUID(uuid);

            itemBean.setExploration_id(exploration_id);//新建踏勘id
            itemBean.setExploration_uuid(exploration_uuid);

//            itemBean.setFeature_id(feature_id);
//            itemBean.setFeature_uuid(feature_uuid);

            handler.sendEmptyMessage(Constant.OPENDIALOG);//打开dialog
            if (imageView == null) {
                SetFileUtil.setExplorationList(itemBean, MyApp.currExploration.getPoint_type());//踏勘点类型
                SetFileUtil.setChannelList(itemBean);//添加特征点
                addImage(itemBean, context, addimage);
                //ProjectStageExplorePointList(exploration_id,number,before_exp,pt_id,pt_type,distance,schedule_id,explor_id,before_lng,before_lat);pt_objectid
                //向缓存中添加点位 channelAList(channel_id,pt_id,distance,exploration_id,number)pt_objectid
                //ProjectExplorePointInfo(number,before_exp,before_number,distance,exploration_type,pt_id,pt_objectid,lng,voltage_grade,lat,location_way,pt)
            }
        }
    }

    private void openDialog() {
        MyLog.L(MString.SUCCESSED + " itemBean=" + JSON.toJSONString(itemBean));
        if (data != null && data.keySet().size() != 0 && data.size() > 0) {
            List<PhotoPassIconBean> dialogBean = itemBean.getDialogBean();
            Set<String> KEY = data.keySet();
            for (PhotoPassIconBean bean : dialogBean) {
                if (KEY.contains(bean.getTitleCode())) {
                    bean.setValuecode(data.get(bean.getTitleCode()) + "");
                    if (bean.getType() == Constant.EdItem) {
                        bean.setValue(bean.getValuecode());
                    } else {
                        List<SystemTypeBean> list = bean.getData();
                        for (SystemTypeBean s : list) {
                            if (s.getTypecode().equals(bean.getValuecode())) {
                                bean.setValue(s.getTypename());
                                break;
                            }
                        }
                    }
                }
            }
        }
        MyDialog.dialogForPhotoPassage(context, itemBean, handler);
    }


}
